package com.it;

import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/pay")
public class PayController {

    @Resource
    private OrderService orderService;

    @RequestMapping("/callback")
    public String success(HttpServletRequest request) throws Exception {
        ServletInputStream is = request.getInputStream();
        byte[] bs = new byte[1024];
        int len = -1;
        StringBuilder builder = new StringBuilder();
        while ((len = is.read(bs)) != -1) {
            builder.append(new String(bs, 0, len));
        }
        String s = builder.toString();
        System.out.println("s = " + s);
        Map<String, String> map = WXPayUtil.xmlToMap(s);
        System.out.println("map.get(\"out_trade_no\") = " + map.get("out_trade_no"));
        if (map != null && "success".equalsIgnoreCase(map.get("result_code"))) {

            //            支付成功
//            2、修改订单状态 待发货、已支付
            String orderId = map.get("out_trade_no");
            int i = orderService.updateOrderStatus(Long.parseLong(orderId));
            //            4、 响应微信支付平台>0)   说，已经支付成功，让微信平台不要再回调确认了
            if (i > 0) {
                Map<String, String> resp = new HashMap<>();
                resp.put("return_code", "success");
                resp.put("return_msg", "OK");
                resp.put("appid", map.get("appid"));
                resp.put("result_code", "success");
                String s1 = WXPayUtil.mapToXml(resp);
                return s1;
            }
            return null;
        } else {
            return null;
        }
    }
}
